<?php
/**
 * Created by PhpStorm.
 * User: wuxiang
 * Date: 2016/7/13
 * Time: 14:28
 * 运营后台渠道包
 */

namespace Channel\Controller;

use Channel\Service\ShortLinkService;
use Common\Controller\AdminbaseController;
use Think\Page;

class ShortlinkController extends AdminbaseController
{

    public function index()
    {
        $page = I('p', 1);
        $pagesize = I('pagesize', 20);
        $data = ShortLinkService::getShortUrlList($page, $pagesize);
        $page = new Page($data['count'], $pagesize, $_GET);
        $this->assign('data', $data);
        $this->assign('pageHtml', $page->show());
        $this->display();
    }




    public function add()
    {
        if(IS_POST) {
            $title = I('title', '', 'trim');
            $checkValue = I('checkValue', '', 'intval');
            $longUrl = I('longUrl', '', 'trim');
            if($checkValue ==2){
                $url = TP_DEBUG ? 'http://m.9now.net/h5/appskip/index.html?openUrl=' : 'http://m.mwee.cn/h5/appskip/index.html?openUrl=';
                $longUrl = $url.$this->reflowURLSafeBase64(base64_encode($longUrl));
            }
            if(empty($title) && !filter_var($longUrl, FILTER_VALIDATE_URL)) {
                $ret = [
                    'status' => 1001,
                    'msg' => '请输入名称和正确的链接'
                ];
                die(json_encode($ret));
            }
            if(empty($title)) {
                $ret = [
                    'status' => 1001,
                    'msg' => '请输入名称'
                ];
                die(json_encode($ret));
            }
            if(!filter_var($longUrl, FILTER_VALIDATE_URL)) {
                $ret = [
                    'status' => 1001,
                    'msg' => '请输入正确的地址'
                ];
                die(json_encode($ret));
            }
            $this->ajaxReturn(ShortLinkService::save($title, $longUrl));
        } else {
            $this->display();
        }
    }

    public function view()
    {
        $id = I('id');
        $detail = ShortLinkService::getShortLinkDetail($id);
        if(!$detail) {
            exit('改链接不存在');
        }
        $data['shortLink'] = $detail;
        $this->assign('data', $data);
        $this->display();
    }

    //url处理base64
    protected  function reflowURLSafeBase64($str){
        $str=str_replace("/","_",$str);
        $str=str_replace("+","-",$str);
        return $str;
    }

    //普通处理base64
    protected  function reflowNormalBase64($str){
        $str=str_replace("_","/",$str);
        $str=str_replace("-","+",$str);
        return $str;
    }
}

